package com.jthinker.base.utils;

import com.jthinker.base.constant.Constant;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by chen.gang on 2014/11/8.
 */
public class WebUtils
{
    /**
     * 获取cookie值
     *
     * @param request
     * @param name
     * @return
     */
    public static String getCookieValue(HttpServletRequest request, String name)
    {
        Cookie[] cookies = request.getCookies();

        if (cookies == null || cookies.length == 0)
        {
            return StringUtils.EMPTY;
        }

        for (Cookie cookie : cookies)
        {
            if (name.equals(cookie.getName()))
            {
                return cookie.getValue();
            }
        }

        return null;
    }

    public static String generateRedirectUrl(String url, String serviceTicket)
    {
        String subfix = "?" + Constant.ST + "=" + serviceTicket;
        //返回跳转前链接
        return "redirect:" + url + subfix;
    }

    /**
     * http://xx.xx.xxx/xx/xxx.xx->http://xx.xx.xxx/xx/
     *
     * @param url
     * @return
     */
    public static String getUrlBasePath(String url)
    {
        String[] temp = StringUtils.split(url, "/");
        return new StringBuilder(temp[0]).append("//").append(temp[1]).append("/").append(temp[2]).append("/").toString();
    }

    public static void main(String[] args)
    {
        System.out.println(getUrlBasePath("http://xxxx.xxx/xx/aa.jsp"));
    }

}
